﻿using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using FBGraph.ClientGenerator.CodeGen;

namespace FBGraph.ClientGenerator
{
    internal class Project
    {
        private const String BASE_NAMESPACE = "FBGraph";

        internal static void AddTypes(CodeGenType[] types)
        {            
            var outputBaseDir = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, @"..\..\..\FBGraph.Api"));

            var projectFile = new VsProjectFile(Path.Combine(outputBaseDir.FullName, "FBGraph.Api.csproj"));
            projectFile.RemoveGeneratedFileReferences();

            foreach (var type in types)
            {
                var namespaceRelativePath = type.Namespace.Replace(BASE_NAMESPACE, String.Empty).Trim('.').Replace('.', '\\');
                var namespacePath = Path.Combine(outputBaseDir.FullName, namespaceRelativePath);

                var fileName = type.Name + ".g.cs";

                String dependentFile;
                var mergeType = projectFile.GetMergeType(Path.Combine(namespaceRelativePath, type.Name), out dependentFile);

                if (mergeType == GeneratedMergeType.DoNotGenerate) continue;
                if (!Directory.Exists(namespacePath)) Directory.CreateDirectory(namespacePath);
                using (var file = File.Open(Path.Combine(namespacePath, fileName), FileMode.Create))
                {
                    using (var writer = new CodeGenWriter(file))
                    {
                        type.Write(writer);
                        writer.Flush();
                    }
                }

                projectFile.AddFileReference(Path.Combine(namespaceRelativePath, fileName), dependentFile);
            }

            projectFile.Save();
        }
    }
}